package com.lightsaber.trade.as.ws.device;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lightsaber.trade.as.service.device.CommandPublishToDeviceManager;
import com.lightsaber.trade.as.service.device.InfoCollectForDeviceManager;
import com.lightsaber.trade.as.ws.api.device.InfoCollectForDeviceDto;
import com.lightsaber.trade.as.ws.api.device.ViewCommand;

@Service("viewCommand")
public class ViewCommandImpl implements ViewCommand {

    final static Logger LOG = LoggerFactory.getLogger(ViewCommandImpl.class);

    @Autowired
    private transient InfoCollectForDeviceManager infoCollectForDeviceManager;
    @Autowired
    private transient CommandPublishToDeviceManager commandPublishToDeviceManager;

    public String hello(String status) {

        LOG.debug("status = {}", status);

        return "I has received your status report.";
    }

    public String collectInfo(String deviceSerialNumber, String content) {

        LOG.debug("deviceSerialNumber={},content={}", deviceSerialNumber, content);

        infoCollectForDeviceManager.save(deviceSerialNumber, content);

        return "OK";
    }

    public InfoCollectForDeviceDto searchCommand(String deviceSerialNumber) {

        LOG.debug("deviceSerialNumber={}", deviceSerialNumber);

        InfoCollectForDeviceDto infoCollectForDeviceDto = null;

        for (int i = 0; i < 5; i++) {
            infoCollectForDeviceDto = commandPublishToDeviceManager.generateDtoFromNoReadCommands(deviceSerialNumber);

            if (infoCollectForDeviceDto.getInfoCollectForDeviceList().size() > 0) {
                break;
            } else {
                try {
                    Thread.sleep(4000L);
                } catch (InterruptedException e) {
                    LOG.error(e.getMessage(), e);
                }
            }
        }

        return infoCollectForDeviceDto;
    }
}
